package com.caocaog.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caocaog.market.constant.MarketConstant;
import com.caocaog.market.entity.Serve;
import com.caocaog.market.mapper.ServeMapper;
import com.caocaog.market.service.ServeService;
import com.caocaog.market.util.DistanceUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.CheckFailedException;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;

/**
 * 服务信息
 *
 * @author chechen
 * @date 2021-11-09
 */
@Service
@Transactional
@RequiredArgsConstructor
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements ServeService {

    private final CommonAPI commonAPI;

    @Override
    public IPage<Serve> queryServePage(Page<Serve> page, Serve serve) {
        this.handleServeByUserType(serve, (LoginUser) SecurityUtils.getSubject().getPrincipal());
        return super.baseMapper.queryServePage(page, serve);
    }

    @Override
    public IPage<Serve> queryServePageByServeType(Page<Serve> page, Serve serve) {
        // 默认上架
        if (serve.getStatus() == null) {
            serve.setStatus(1);
        }
        return super.baseMapper.queryServePage(page, serve);
    }

    @Override
    public List<Serve> getLatestList(Serve serve) {
        if (StringUtils.isBlank(serve.getSiteId())) {
            throw new CheckFailedException("分站id不能为空");
        }
        return super.baseMapper.selectList(
                new LambdaQueryWrapper<Serve>().eq(Serve::getSiteId, serve.getSiteId()).orderByDesc(Serve::getCreateTime).last("limit 10"));
    }

    @Override
    public String addServe(Serve serve) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        this.handleServeByUserType(serve, loginUser);
        if (StringUtils.isBlank(loginUser.getCurrentSelectedShopId())) {
            throw new JeecgBootException("用户暂未绑定门店, realName-> " + loginUser.getRealname());
        }
        /*if (StringUtils.isNotBlank(serve.getImagesBottomString())) {
            serve.setImagesBottom(Arrays.asList(serve.getImagesBottomString().split(",")));
        }
        if (StringUtils.isNotBlank(serve.getImagesCarouselString())) {
            serve.setImagesCarousel(Arrays.asList(serve.getImagesCarouselString().split(",")));
        }*/
        serve.setCreateTime(new Date());
        serve.setCreateBy(loginUser.getUsername());
        serve.setDelFlag(CommonConstant.DEL_FLAG_0);
        serve.setLockVersion(1);
        serve.setStatus(0);
        serve.setShopId(loginUser.getCurrentSelectedShopId());
        System.out.println(serve);

        super.baseMapper.insert(serve);
        if (serve.getId() == null) {
            throw new JeecgBootException("新增服务失败");
        }
        return serve.getId();
    }

    /**
     * 根据用户类型处理服务信息实体数据
     *
     * @param serve     服务信息实体
     * @param loginUser 当前登录用户
     */
    private void handleServeByUserType(Serve serve, LoginUser loginUser) {
        // 根据用户类型判断
        if (MarketConstant.USER_TYPE_SITE.equals(loginUser.getUserType())) {
            if (StringUtils.isBlank(loginUser.getSiteId())) {
                throw new JeecgBootException("用户暂未绑定分站, realName-> " + loginUser.getRealname());
            }
            // 分站类型默认 查询该分站下的数据/插入分站
            serve.setSiteId(loginUser.getSiteId());
        } else if (MarketConstant.USER_TYPE_MERCHANT.equals(loginUser.getUserType())) {
            if (StringUtils.isBlank(loginUser.getMerchantId())) {
                throw new JeecgBootException("用户暂未绑定商家, realName-> " + loginUser.getRealname());
            }
            String siteId = commonAPI.getSiteIdByMerchantId(loginUser.getMerchantId());
            if (StringUtils.isBlank(siteId)) {
                throw new JeecgBootException("商家暂未绑定分站, realName-> " + loginUser.getRealname());
            }
            // 商家类型默认 查询该商家下的数据/插入商家
            serve.setSiteId(siteId);
            serve.setMerchantId(loginUser.getMerchantId());
            serve.setShopId(loginUser.getCurrentSelectedShopId());
        }
    }

    @Override
    public int updateServe(Serve serve) {
        serve.setUpdateTime(new Date());
        serve.setDelFlag(null);
        serve.setUpdateBy(((LoginUser) SecurityUtils.getSubject().getPrincipal()).getUsername());

        /*if (StringUtils.isNotBlank(serve.getImagesBottomString())) {
            serve.setImagesBottom(Arrays.asList(serve.getImagesBottomString().split(",")));
        }
        if (StringUtils.isNotBlank(serve.getImagesCarouselString())) {
            serve.setImagesCarousel(Arrays.asList(serve.getImagesCarouselString().split(",")));
        }*/
        System.out.println(serve);

        int updateRecordCount = super.baseMapper.updateById(serve);
        if (updateRecordCount == 0) {
            throw new JeecgBootException("更新服务失败, id-> " + serve.getId());
        }
        return updateRecordCount;
    }

    @Override
    public int putOnSaleServe(String ids) {
        int putOnSaleRecordCount = this.upDownServe(1, ids);
        if (putOnSaleRecordCount == 0) {
            throw new JeecgBootException("服务上架失败, ids-> " + ids);
        }
        return putOnSaleRecordCount;
    }

    @Override
    public int pullOffShelvesServe(String ids) {
        int pullOffShelvesRecordCount = this.upDownServe(0, ids);
        if (pullOffShelvesRecordCount == 0) {
            throw new JeecgBootException("服务下架失败, ids-> " + ids);
        }
        return pullOffShelvesRecordCount;
    }

    private int upDownServe(Integer status, String ids) {
        return super.baseMapper.update(null, Wrappers.<Serve>lambdaUpdate()
                .set(Serve::getStatus, status)
                .apply(String.format("FIND_IN_SET('%s',id)", ids)));
    }

    @Override
    public int deleteServe(String id) {
        int deleteRecordCount = super.baseMapper.deleteById(id);
        if (deleteRecordCount == 0) {
            throw new JeecgBootException("删除服务信息失败, id-> " + id);
        }
        return deleteRecordCount;
    }

    @Override
    public int deleteBatchServe(List<String> ids) {
        int deleteRecordCount = super.baseMapper.deleteBatchIds(ids);
        if (deleteRecordCount < ids.size()) {
            throw new JeecgBootException(
                    String.format("批量删除服务信息失败, deleteRecordCount-> %s, ids.size()-> %s, ids-> %s",
                            deleteRecordCount, ids.size(), ids));
        }
        return deleteRecordCount;
    }

    @Override
    public List<Serve> getSurroundingServe(String lat, String lng, String serveType) {
        List<Serve> serveList = super.baseMapper.selectByTypeAndShopLatLng(serveType);
        //计算每个店铺的距离
        return serveList.stream().peek(serve -> {
            Double distance = DistanceUtil.getDistanceMeter(Double.parseDouble(lat), Double.parseDouble(lng),
                    Double.parseDouble(serve.getLat()), Double.parseDouble(serve.getLng()));
            serve.setDistance(Double.parseDouble(String.format("%.2f", distance)));
        }).filter(item -> item.getDistance() < 25).sorted(comparing(Serve::getDistance)).collect(Collectors.toList());
    }
}
